from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from .serializers import CouponTypeSer,CouponSer

# Create your views here.

# 优惠券类型信息视图
class TypesView(APIView):
    def get(self,request):
        coupon = CouponType.objects.all()

        ser = CouponTypeSer(coupon,many=True)

        return Response(ser.data)


# 获取优惠券信息
class CouponsView(APIView):
    def get(self,request):
        coupon = Coupon.objects.all()

        ser = CouponSer(coupon,many=True)

        return Response(ser.data)




    # 添加
    def post(self,request):
        ser = CouponSer(data=request.data)
        print('dasfasf',ser)
        result = ser.is_valid(raise_exception=True)
        print('dasfasf',result)
        if result:
            # 校验没有问题
            ser.save()

        else:
            print('添加失败',ser.error_messages)
            return Response({
                'code':400,
                'msg':'添加失败'
            })
        return Response({
            'code': 201,
            'msg': '添加成功'
        })

# 编辑删除获取
class CouponssView(APIView):
    def get(self,request,id):
        try:
            coupon = Coupon.objects.get(id=id)
        except Exception as e:
            print('获取失败信息',e)
            return Response({
                'code':400,
                'msg':'获取失败'
            })

        ser = CouponSer(coupon)

        return Response(ser.data)

    # 编辑
    def put(self,request,id):
        try:
            coupon = Coupon.objects.get(id=id)
        except Exception as e:
            print('获取失败信息',e)
            return Response({
                'code':400,
                'msg':'获取失败'
            })

        ser = CouponSer(instance=coupon,data=request.data)

        result = ser.is_valid(raise_exception=True)

        print('dasfasf', result)
        if result:
            # 校验没有问题
            ser.save()

        else:
            print('修改失败', ser.error_messages)
            return Response({
                'code': 400,
                'msg': '修改失败'
            })
        return Response({
            'code': 200,
            'msg': '修改成功'
        })

    # 删除的信息
    def delete(self,request,id):
        try:
            Coupon.objects.get(id=id).delete()
        except Exception as e:
            print('获取失败信息',e)
            return Response({
                'code':400,
                'msg':'删除失败'
            })

        return Response({
            'code':204,
            'msg':'删除成功'
        })
